package com.snack.shop.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Web配置
 */
@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${file.upload.path:/tmp/uploads}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 处理上传路径（支持相对路径）
        File uploadDir = new File(uploadPath);
        if (!uploadDir.isAbsolute()) {
            uploadDir = new File(System.getProperty("user.dir"), uploadPath);
        }
        
        // 规范化路径，解析 .. 和 .
        String absolutePath = uploadDir.getAbsolutePath();
        try {
            absolutePath = uploadDir.getCanonicalPath();
        } catch (java.io.IOException e) {
            log.warn("获取规范路径失败，使用绝对路径: {}", absolutePath);
        }
        // 确保路径以斜杠结尾
        if (!absolutePath.endsWith(File.separator)) {
            absolutePath += File.separator;
        }
        
        String locationPath = "file:" + absolutePath;
        log.info("========== 配置静态资源访问 ==========");
        log.info("配置的上传路径: {}", uploadPath);
        log.info("绝对路径: {}", absolutePath);
        log.info("文件位置映射: {}", locationPath);
        log.info("资源处理器映射: /uploads/** 和 /api/uploads/** -> {}", locationPath);
        log.info("目录是否存在: {}", uploadDir.exists());
        log.info("目录是否可读: {}", uploadDir.canRead());
        if (uploadDir.exists()) {
            File[] files = uploadDir.listFiles();
            log.info("目录下文件数: {}", files != null ? files.length : 0);
        }
        log.info("=====================================");
        
        // 配置静态资源访问（同时兼容 /uploads/** 和 /api/uploads/**）
        registry.addResourceHandler("/uploads/**", "/api/uploads/**")
                .addResourceLocations(locationPath)
                .setCachePeriod(3600)  // 缓存1小时
                .resourceChain(true)
                .addResolver(new org.springframework.web.servlet.resource.PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, org.springframework.core.io.Resource location) throws java.io.IOException {
                        log.debug("请求资源路径: {}", resourcePath);
                        Resource resource = super.getResource(resourcePath, location);
                        log.debug("资源是否存在: {}, 资源路径: {}", resource != null && resource.exists(), resource != null ? resource.getFilename() : "null");
                        return resource;
                    }
                });
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 配置字符串消息转换器，使用UTF-8编码
        StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        converters.add(0, converter);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 配置CORS，允许跨域访问上传的文件
        registry.addMapping("/uploads/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD")
                .allowCredentials(true)
                .maxAge(3600);
        
        registry.addMapping("/api/uploads/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD")
                .allowCredentials(true)
                .maxAge(3600);
    }
}